package com.moorwind.chartservice.utils
{
	import com.moorwind.chartservice.utils.hurlant.Base64;
	import com.moorwind.chartservice.utils.hurlant.HMAC;
	import com.moorwind.chartservice.utils.hurlant.Hex;
	import com.moorwind.chartservice.utils.hurlant.SHA1;
	
	import flash.net.URLVariables;
	import flash.utils.ByteArray;
	
	public class CryptoUtils
	{
		public static function createSinature(key:String, param:URLVariables):String
		{
			return HMAC_SHA1(key, createBaseString(param));
		}
		
		public static function createBaseString(param:URLVariables):String
		{			
        	var raw:String = "";
        	
			raw += "user_name=" + encodeURIComponent(param.user_name);
			raw += "&user_id=" + encodeURIComponent(param.user_id);
			raw += "&user_link=" + encodeURIComponent(param.user_link);
			raw += "&user_image=" + encodeURIComponent(param.user_image);
			raw += "&user_large_image=" + encodeURIComponent(param.user_large_image);
			raw += "&platform=" + encodeURIComponent(param.platform);
			raw += "&score=" + encodeURIComponent(param.score);
			raw += "&chart_id=" + encodeURIComponent(param.chart_id);
			raw += "&chart_name=" + encodeURIComponent(param.chart_name);
			
			return raw;
		}
		
		public static function HMAC_SHA1(key:String, raw:String):String
		{
			trace(key);
			trace(raw);
			var keyData:ByteArray, cryptoData:ByteArray;
			var hmac:HMAC  	= new HMAC( new SHA1 );			
			keyData 		= Hex.toArray( Hex.fromString( key) );
			cryptoData  	= Hex.toArray( Hex.fromString( raw ) );
			
			var outDate:ByteArray = hmac.compute( keyData, cryptoData );
			
			if( !outDate )
				throw new Error( "Crypto Error" );
						
			return Base64.encodeByteArray( outDate );
		}

	}
}